package com.liunian.algorithmstudy.tree;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

public class LevelOrderBottom107 extends TreeNode {

	public List<List<Integer>> levelOrderBottom(TreeNode root) {
		if (root == null) {
			return Collections.emptyList();
		}
		Deque<TreeNode> deque = new LinkedList<>();
		List<List<Integer>> res = new ArrayList<>();
		deque.push(root);
		while (!deque.isEmpty()) {
			int size = deque.size();
			List<Integer> temp = new ArrayList<>();
			while (size-- > 0) {
				TreeNode treeNode = deque.pollFirst();
				temp.add(treeNode.val);
				if (treeNode.left != null) {
					deque.addLast(treeNode.left);
				}
				if (treeNode.right != null) {
					deque.addLast(treeNode.right);
				}
			}
			res.add(temp);
		}
		reverse(res);
		return res;
	}

	private void reverse(List<List<Integer>> res) {
		int left = 0;
		int right= res.size() - 1;
		while (left < right) {
			List<Integer> temp = res.get(left);
			res.set(left, res.get(right));
			res.set(right, temp);
			left++;
			right--;
		}
	}

}
